/**
 * 
 */
package soa.security.web;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

import soa.security.dao.AccountDao;
import soa.security.dao.OrganizationDao;
import soa.security.domain.Account;
import soa.security.domain.Organization;
import soa.security.domain.Person;
import soa.security.mgr.service.PersonMgrService;
import v1.security.web.V1AuthenticationFilter;

/**
 * @author Cre.Gu
 *
 */
public class LdapAuthenticationFilter extends V1AuthenticationFilter {

	public final static String SESSION_ORGANIZATION_KEY = "_organization_key";
	public final static String SESSION_ACCOUNT_KEY = "_account_key";

	@Resource
	protected AccountDao accountDao;
	@Resource
	protected OrganizationDao organizationDao;
	@Resource
	protected PersonMgrService personMgrService;

	@Override
	public boolean doCaptchaValidate(ServletRequest request,
			ServletResponse response) {
		return true;
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		boolean flag = super.onLoginSuccess(token, subject, request, response);

		String accountDn = (String) subject.getPrincipal();
		Account account = accountDao.findByDn(accountDn);

		try {
			String organizationDn = WebUtils.getCleanParam(request,
					"organizationDn");
			if (StringUtils.isNotBlank(organizationDn) && !"-1".equals(organizationDn)) {
				Organization or = organizationDao.findByDn(organizationDn);
				subject.getSession().setAttribute(SESSION_ORGANIZATION_KEY, or);

				Person person = personMgrService.findByUid(account.getPersonBid(),
						or.getBid());
				account.setPerson(person);
			}
		} catch (Exception e) {
		}

		subject.getSession().setAttribute(SESSION_ACCOUNT_KEY, account);
		return flag;
	}

	@Override
	protected void doDetail(Subject subject) {

	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {
		String organizationDn = WebUtils.getCleanParam(request,
				"organizationDn");

		return new LdapUsernamePasswordCaptchaToken(getUsername(request),
				getPassword(request), isRememberMe(request), getHost(request),
				getCheckpass(request), organizationDn);
	}

}
